package com.jacklin.converter;

import com.jacklin.DTO.OrderDTO;
import com.jacklin.entity.OrderDetail;
import com.jacklin.enums.ResultEnum;
import com.jacklin.exception.MyException;
import com.jacklin.form.OrderForm;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:JackLin
 * @Create 2019/3/30 13:24
 */

@Slf4j
public class OrderForm2OrderDTOConverter {

    public static OrderDTO convert(OrderForm orderForm){

        Gson gson = new Gson();

        OrderDTO orderDTO = new OrderDTO();
        //        BeanUtils.copyProperties(orderForm, orderDTO);这里不适用beanUtil方法转原因是orderForm里面的属性名和OrderDTO里面的属性名不一致
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());

        List<OrderDetail> orderDetailList = new ArrayList<>();

        try {
            //json格式转换为返回前端的字符串格式，如果不是json格式，则抛出异常
            orderDetailList = gson.fromJson(orderForm.getItems(),new TypeToken<List<OrderDetail>>(){}.getType());
        }catch (Exception e){
            log.info("【对象转换】错误，string={}", orderForm.getItems());
            throw new MyException(ResultEnum.PARAM_ERROR);
        }
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;

    }
}
